/**
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Modal, Spin, Transfer, message } from "antd";
import axios from "../../../../apis/api";
import qs from "qs";

class EditGroupUser extends Component {
  static propTypes = {
    visible: PropTypes.bool.isRequired
  };
  state = {
    targetKeys: [],
    selectedKeys: [],
    data: [],
    loading: false
  };

  componentDidMount() {}

  async componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible && !this.props.visible) {
      const {
        groupUserList: { all, groupUser }
      } = nextProps;
      const targetKeys = groupUser.rows.map(item => item.userId);
      const data = all.rows.map(item => {
        return {
          key: item.userId,
          title: item.userName
        };
      });
      this.setState({ targetKeys, data });
    }
  }

  handleChange = (nextTargetKeys, direction, moveKeys) => {
    this.setState({ targetKeys: nextTargetKeys });

    console.log("targetKeys: ", nextTargetKeys);
    console.log("direction: ", direction);
    console.log("moveKeys: ", moveKeys);
  };

  handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    this.setState({
      selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys]
    });
  };

  handleOk = () => {
    const { targetKeys } = this.state;
    const { userInfo, cancelCb } = this.props;
    const { userId } = userInfo;
    this.setState({ loading: true });
    axios
      .post(
        "/system/user/updateGroupUser",
        qs.stringify({ groupId: userId, userIds: targetKeys.join(",") })
      )
      .then(res => {
        if (res.code === 0) {
          message.success(res.msg);
          cancelCb();
        } else {
          message.error(res.msg);
        }
        this.setState({ loading: false });
      })
      .catch(e => {
        console.log(e);
        message.error(e.message || e.msg);
        this.setState({ loading: false });
      });
  };

  render() {
    const { visible, title, allUsers, cancelCb } = this.props;
    const { data, targetKeys, selectedKeys, loading } = this.state;

    return (
      <Modal
        title={title}
        visible={visible}
        width={700}
        onOk={this.handleOk}
        onCancel={cancelCb}
        okText={"确认"}
        cancelText={"取消"}
      >
        <Spin spinning={loading}>
          <Transfer
            listStyle={{ width: 300, height: 500 }}
            dataSource={data}
            titles={["所有业务员", "选中的业务员"]}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            onChange={this.handleChange}
            onSelectChange={this.handleSelectChange}
            onScroll={this.handleScroll}
            render={item => item.title}
          />
        </Spin>
      </Modal>
    );
  }
}

export default EditGroupUser;
